//    Copyright (C) 2013  <lugocreation@gmail.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>
package org.jpgolay.wi.user;

import java.awt.Dimension;
import java.awt.event.*;
import java.awt.print.PrinterJob;
import java.beans.PropertyVetoException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
import org.jpgolay.gui.iconBar.*;
import org.jpgolay.gui.progressBar.ProgressBar;
import org.jpgolay.gui.progressBar.SwingWorker;
import org.jpgolay.wi.agency.Agency;
import org.jpgolay.wi.agency.AgencyCRUD;
import org.jpgolay.wi.group.Group;
import org.jpgolay.wi.group.GroupCRUD;
import org.jpgolay.wi.list.ListController;
import org.jpgolay.wi.util.BrowserControl;
import org.jpgolay.wi.util.WIDate;

// Referenced classes of package org.jpgolay.wi.user:
//            UserGUI, UserCRUD, User, UserList
public class UserController {

    private class MouseClickList extends MouseAdapter {

        public void mouseClicked(MouseEvent e) {
            actionSelectUser();
        }

        MouseClickList() {
        }
    }

    public UserController(String agencyId) {
        this.agencyId = "";
        id = "";
        action = 0;
        this.agencyId = agencyId;
        initComponent();
        date = new WIDate();
        uGui.editableFields(false);
    }

    private boolean initComponent() {
        if (crud == null) {
            crud = new UserCRUD();
            crudAgency = new AgencyCRUD();
            crudGroup = new GroupCRUD();
        }
        if (uGui == null || uGui.isClosed()) {
            uGui = new UserGUI();
            uGui.setIconifiable(true);
            uGui.setResizable(false);
            uGui.setMaximizable(false);
            uGui.setClosable(true);
            uGui.setVisible(true);
            uGui.toFront();
            uGui.getSaveMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent actionevent) {
                }
            });
            uGui.getNewMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionCreate();
                }
            });
            uGui.getOpenMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionOpen();
                }
            });
            uGui.getModifyMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionModify();
                }
            });
            uGui.getSaveMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionSave();
                }
            });
            uGui.getRemoveMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionRemove();
                }
            });
            uGui.getHelpMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionHelp();
                }
            });
            uGui.getPrintMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    PrinterJob pj = PrinterJob.getPrinterJob();
                    if (pj.printDialog()) {
                        actionPrint();
                    }
                }
            });
            uGui.getIconBar1().addAnswerListener(new AnswerListener() {
                public void create(AnswerEvent e) {
                    actionCreate();
                }

                public void open(AnswerEvent e) {
                    actionOpen();
                }

                public void modify(AnswerEvent e) {
                    actionModify();
                }

                public void save(AnswerEvent e) {
                    actionSave();
                }

                public void remove(AnswerEvent e) {
                    actionRemove();
                }

                public void print(AnswerEvent e) {
                    actionPrint();
                }

                public void help(AnswerEvent e) {
                    actionHelp();
                }
            });
            uGui.setAllAgencyId(getAllAgency());
            uGui.setAllGroupId(getAllGroup());
            return true;
        }
        if (uGui.isIcon()) {
            try {
                uGui.setIcon(false);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }
        }
        uGui.toFront();
        return false;
    }

    public boolean init() {
        if (uGui == null || uGui.isClosed()) {
            boolean result = initComponent();
            uGui.editableFields(false);
            if (result) {
                setLaw();
            }
            return result;
        }
        if (uGui.isIcon()) {
            try {
                uGui.setIcon(false);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }
        }
        uGui.toFront();
        return false;
    }

    private void actionCreate() {
        if (action == 2) {
            JOptionPane.showMessageDialog(uGui, "Modification en cours !");
        } else {
            action = 1;
            uGui.initFields();
            uGui.editableFields(true);
        }
    }

    private void actionOpen() {
        uGui.initFields();
        uGui.editableFields(false);
        openList();
    }

    private void actionModify() {
        if (action == 1) {
            JOptionPane.showMessageDialog(uGui, "Modification impossible !");
        } else {
            action = 2;
            uGui.editableFields(true);
        }
    }

    private void actionSave() {
        if (action == 2 || action == 1) {
            setUser();
        } else {
            JOptionPane.showMessageDialog(uGui, "Aucunes donn\351es \340 sauvegarder !");
        }
    }

    private void actionRemove() {
        if (action == 2) {
            remove();
        } else {
            JOptionPane.showMessageDialog(uGui, "Aucunes donn\351es \340 supprimer !");
        }
    }

    private void actionPrint() {
    }

    private void actionHelp() {
        BrowserControl.displayURL("www.ifacile.com");
    }

    private void actionSelectUser() {
        getUser(new Integer(lCtrl.getContenuT().getValueAt(lCtrl.getContenuT().getSelectedRow(), 0).toString()));
        lCtrl.hidden();
    }

    private void getUser(Integer id) {
        final Integer ID = id;
        SwingWorker worker = new SwingWorker() {
            public Object construct() {
                startProgressBar();
                if (crud.find(ID.toString())) {
                    user = crud.getData();
                    uGui.setAccess(user.getAccess().intValue());
                    uGui.setGroupId(indexGroup.indexOf(user.getGroupId()));
                    uGui.setAddrLn1(user.getAddrLn1());
                    uGui.setAddrLn2(user.getAddrLn2());
                    uGui.setCity(user.getCity());
                    uGui.setComment(user.getComment());
                    uGui.setFirstname(user.getFirstname());
                    uGui.setCounty(user.getCounty());
                    uGui.setEmail(user.getEmail());
                    uGui.setExpiryDate(user.getExpiryDate());
                    uGui.setFax(user.getFax());
                    uGui.setId(user.getId().toString());
                    uGui.setLastUpdate(user.getLastUpdate());
                    uGui.setLastUser(user.getLastUser());
                    uGui.setLogo(user.getLogo());
                    uGui.setPass(user.getPass());
                    uGui.setPaymentDue(user.getPaymentDue().toString());
                    uGui.setAgencyId(indexAgency.indexOf(user.getAgencyId()));
                    uGui.setLastname(user.getLastname());
                    uGui.setTel1(user.getTel1());
                    uGui.setTel2(user.getTel2());
                    uGui.setUsername(user.getUsername());
                    uGui.setWeb(user.getWeb());
                    uGui.setZip(user.getZip());
                } else {
                    JOptionPane.showMessageDialog(uGui, "Impossible de r\351cuperer l'agence !");
                }
                stopProgressBar();
                return null;
            }
        };
        worker.start();
    }

    private void setUser() {
        if (verifyRequis()) {
            SwingWorker worker = new SwingWorker() {
                public Object construct() {
                    startProgressBar();
                    if (uGui.getId().equals("")) {
                        if (crud.create()) {
                            user = crud.getData();
                            user.setGroupId(new Integer(uGui.getGroupId()));
                            user.setAccess(new Integer(uGui.getAccess()));
                            user.setAddrLn1(uGui.getAddrLn1());
                            user.setAddrLn2(uGui.getAddrLn2());
                            user.setCity(uGui.getCity());
                            user.setComment(uGui.getComment());
                            user.setFirstname(uGui.getFirstname());
                            user.setCounty(uGui.getCounty());
                            user.setEmail(uGui.getEmail());
                            user.setExpiryDate(uGui.getExpiryDate());
                            user.setFax(uGui.getFax());
                            user.setLastUser(usr.getId().toString());
                            user.setLogo(uGui.getLogo());
                            user.setPass(uGui.getPass());
                            user.setPaymentDue(new BigDecimal(uGui.getPaymentDue()));
                            user.setAgencyId(new Integer(uGui.getAgencyId()));
                            user.setLastname(uGui.getLastname());
                            user.setTel1(uGui.getTel1());
                            user.setTel2(uGui.getTel2());
                            user.setUsername(uGui.getUsername());
                            user.setWeb(uGui.getWeb());
                            user.setZip(uGui.getZip());
                            crud.setData(user);
                            if (crud.modify()) {
                                uGui.editableFields(false);
                                action = 0;
                            } else {
                                JOptionPane.showMessageDialog(uGui, "Impossible de r\351cuperer l'utilisateur !\n(un autre utilisateur l'a peut-\352tre modifi\351e)");
                            }
                        } else {
                            JOptionPane.showMessageDialog(uGui, "Impossible de r\351cuperer l'utilisateur !\n(un autre utilisateur l'a peut-\352tre supprim\351)");
                        }
                    } else if (crud.find(uGui.getId())) {
                        user = crud.getData();
                        user.setGroupId(new Integer(uGui.getGroupId()));
                        user.setAccess(new Integer(uGui.getAccess()));
                        user.setAddrLn1(uGui.getAddrLn1());
                        user.setAddrLn2(uGui.getAddrLn2());
                        user.setCity(uGui.getCity());
                        user.setComment(uGui.getComment());
                        user.setFirstname(uGui.getFirstname());
                        user.setCounty(uGui.getCounty());
                        user.setEmail(uGui.getEmail());
                        user.setExpiryDate(uGui.getExpiryDate());
                        user.setFax(uGui.getFax());
                        user.setLastUpdate(uGui.getLastUpdate());
                        user.setLastUser(usr.getId().toString());
                        user.setLogo(uGui.getLogo());
                        user.setPass(uGui.getPass());
                        user.setPaymentDue(new BigDecimal(uGui.getPaymentDue()));
                        user.setAgencyId(new Integer(uGui.getAgencyId()));
                        user.setLastname(uGui.getLastname());
                        user.setTel1(uGui.getTel1());
                        user.setTel2(uGui.getTel2());
                        user.setUsername(uGui.getUsername());
                        user.setWeb(uGui.getWeb());
                        user.setZip(uGui.getZip());
                        crud.setData(user);
                        if (crud.modify()) {
                            uGui.editableFields(false);
                            action = 0;
                        } else {
                            JOptionPane.showMessageDialog(uGui, "Impossible de modifi\351e l'utilisateur !\n(un autre utilisateur l'a peut-\352tre modifi\351e)");
                        }
                    } else {
                        JOptionPane.showMessageDialog(uGui, "Impossible de r\351cuperer l'utilisateur !\n(un autre utilisateur l'a peut-\352tre supprim\351)");
                    }
                    stopProgressBar();
                    return null;
                }
            };
            worker.start();
        }
    }

    private void remove() {
        int reponse = JOptionPane.showConfirmDialog(uGui, "Voulez-vous vraiment supprimer l'utilisateur num\351ro " + uGui.getId() + " ?", "Confirmation", 1, 2, null);
        switch (reponse) {
            case -1:
            case 1: // '\001'
            case 2: // '\002'
            default:
                break;

            case 0: // '\0'
                if (crud.find(uGui.getId())) {
                    if (crud.remove()) {
                        uGui.initFields();
                        uGui.editableFields(false);
                        action = 0;
                    } else {
                        JOptionPane.showMessageDialog(uGui, "Impossible de supprimer l'utilisateur  (" + uGui.getId() + ") !" + "\nUn autre utilisateur l'a peut-\352tre modifi\351 entre temps.");
                    }
                } else {
                    JOptionPane.showMessageDialog(uGui, "Impossible de trouver l'utilisateur  (" + uGui.getId() + ") !" + "\nUn autre utilisateur l'a peut-\352tre supprimer entre temps.");
                }
                break;
        }
    }

    private boolean verifyRequis() {
        if (uGui.getAddrLn1().length() > 250) {
            JOptionPane.showMessageDialog(uGui, "Adresse ligne 1 trop longue !\n(maximum 250 caract\350res)");
            return false;
        }
        if (uGui.getAddrLn2().length() > 250) {
            JOptionPane.showMessageDialog(uGui, "Adresse ligne 2 trop longue !\n(maximum 250 caract\350res)");
            return false;
        }
        if (uGui.getCity().length() > 250) {
            JOptionPane.showMessageDialog(uGui, "Ville trop longue !\n(maximum 250 caract\350res)");
            return false;
        }
        if (uGui.getComment().length() > 250) {
            JOptionPane.showMessageDialog(uGui, "Commentaire trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (uGui.getFirstname().length() > 250) {
            JOptionPane.showMessageDialog(uGui, "Pr\351nom trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (uGui.getCounty().length() > 250) {
            JOptionPane.showMessageDialog(uGui, "Commune trop longue !\n(maximum 250 caract\350res)");
            return false;
        }
        if (uGui.getEmail().length() > 250) {
            JOptionPane.showMessageDialog(uGui, "E-mail trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (uGui.getFax().length() > 250) {
            JOptionPane.showMessageDialog(uGui, "Fax trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (uGui.getPass().length() > 250) {
            JOptionPane.showMessageDialog(uGui, "Mot de passe trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (uGui.getPass().length() < 4) {
            JOptionPane.showMessageDialog(uGui, "Mot de passe requis !\n(minimum 4 caract\350res)");
            return false;
        }
        if (uGui.getLastname().length() > 250) {
            JOptionPane.showMessageDialog(uGui, "Nom trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (uGui.getTel1().length() > 250) {
            JOptionPane.showMessageDialog(uGui, "T\351l 1 trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (uGui.getTel2().length() > 250) {
            JOptionPane.showMessageDialog(uGui, "T\351l 2 trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (uGui.getUsername().length() > 250) {
            JOptionPane.showMessageDialog(uGui, "Nom d'utilisateur trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (uGui.getWeb().length() > 250) {
            JOptionPane.showMessageDialog(uGui, "Web trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (uGui.getZip().length() > 5) {
            JOptionPane.showMessageDialog(uGui, "Code postal trop long !\n(maximum 5 caract\350res)");
            return false;
        }
        if (uGui.getPaymentDue().equals("")) {
            uGui.setPaymentDue("0");
        }
        if (!date.isValid(uGui.getExpiryDate())) {
            uGui.setExpiryDate("");
        }
        try {
            new BigDecimal(uGui.getPaymentDue());
        } catch (NumberFormatException nfe3) {
            JOptionPane.showMessageDialog(uGui, "Le montant Paiement du est invalide !");
            return false;
        }
        try {
            new Integer(uGui.getZip());
        } catch (NumberFormatException nfe1) {
            JOptionPane.showMessageDialog(uGui, "Code postal invalide !\n(nombre entier uniquement)");
            return false;
        }
        if (action == 1 && crud.isPassword(uGui.getPass())) {
            JOptionPane.showMessageDialog(uGui, "Le mot de passe (" + uGui.getPass() + ") existe d\351j\340 !");
            return false;
        } else {
            return true;
        }
    }

    private String[] getAllAgency() {
        ArrayList list = new ArrayList(crudAgency.findAll());
        if (list != null && list.size() > 0) {
            Iterator it = list.iterator();
            String l[] = new String[list.size()];
            indexAgency = new ArrayList();
            for (int i = 0; it.hasNext(); i++) {
                agency = (Agency) it.next();
                l[i] = agency.getId().toString() + " " + agency.getCompagny() + " " + agency.getCity();
                indexAgency.add(agency.getId());
            }

            return l;
        } else {
            String e[] = {
                "Aucune agence"
            };
            return e;
        }
    }

    private String[] getAllGroup() {
        ArrayList list = new ArrayList(crudGroup.findAll());
        if (list != null && list.size() > 0) {
            Iterator it = list.iterator();
            String l[] = new String[list.size()];
            indexGroup = new ArrayList();
            for (int i = 0; it.hasNext(); i++) {
                group = (Group) it.next();
                l[i] = group.getId().toString() + " " + group.getName();
                indexGroup.add(group.getId());
            }

            return l;
        } else {
            String e[] = {
                "Aucun group"
            };
            return e;
        }
    }

    public void iconified() {
        if (uGui != null) {
            uGui.setVisible(false);
        }
    }

    public void unIconified() {
        if (uGui != null) {
            uGui.setVisible(true);
        }
    }

    public void maximizeFrame() {
        try {
            uGui.setSelected(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }

    private void startProgressBar() {
        if (pb == null) {
            pb = new ProgressBar(null, false);
            pb.setLocationRelativeTo(uGui);
            uGui.setEnabled(false);
            pb.setVisible(true);
            pb.start();
        } else {
            uGui.setEnabled(false);
            pb.setVisible(true);
            pb.start();
        }
    }

    private void stopProgressBar() {
        if (!pb.isStop()) {
            pb.stop();
            pb.setVisible(false);
            uGui.setEnabled(true);
        }
    }

    private void setLaw() {
        String b = Long.toBinaryString(usr.getAccess().intValue());
        int position = b.length();
        if ((position -= 14) >= 0 && b.charAt(position) == '1') {
            uGui.getNewMI().setEnabled(true);
            uGui.getModifyMI().setEnabled(true);
            uGui.getRemoveMI().setEnabled(true);
            uGui.getSaveMI().setEnabled(true);
            uGui.getIconBar1().setEnabledCreate(true);
            uGui.getIconBar1().setEnabledModify(true);
            uGui.getIconBar1().setEnabledRemove(true);
            uGui.getIconBar1().setEnabledSave(true);
        }
    }

    public void setUser(User user) {
        usr = user;
        setLaw();
    }

    public UserGUI getGUI() {
        return uGui;
    }

    public void setJDesktopPane(JDesktopPane desktop) {
        this.desktop = desktop;
    }

    private void openList() {
        if (lCtrl == null) {
            lCtrl = new ListController("logo.gif", desktop, "Liste des UTILISATEURS", UserList.CB_MODEL, UserList.COLUMN_NAME);
            lCtrl.setPreferredColumnSize(UserList.COLUMN_SIZE);
            lCtrl.setRequestChoice(UserList.REQUESTS);
            lCtrl.setRequestLikeChoice(UserList.REQUESTS_LIKE);
            lCtrl.setRequestErrorMsg(UserList.ERROR_MSG);
            lCtrl.getContenuT().addMouseListener(new MouseClickList());
        } else {
            lCtrl.getContenuT().addMouseListener(new MouseClickList());
            lCtrl.show();
        }
        lCtrl.search();
    }

    private void closeList() {
        lCtrl.close();
    }
    private UserGUI uGui;
    private UserCRUD crud;
    private AgencyCRUD crudAgency;
    private GroupCRUD crudGroup;
    private Agency agency;
    private Group group;
    private User user;
    private User usr;
    private String agencyId;
    private Dimension screen;
    private WIDate date;
    private ProgressBar pb;
    private ListController lCtrl;
    private ArrayList indexGroup;
    private ArrayList indexAgency;
    private String id;
    private int action;
    private final int CREATE = 1;
    private final int MODIFY = 2;
    private JDesktopPane desktop;
}
